<?php
/**
 * Created by PhpStorm.
 * User: ari
 * Date: 11/18/14
 * Time: 8:14 PM
 */
namespace BC\User;

use BC\PGP\Commands\PGPSearchCommand;
use BC\PGP\PGPConfig;
use CPath\Data\Map\IKeyMap;
use CPath\Data\Map\IKeyMapper;
use CPath\Request\IRequest;
use CPath\Request\IRequestAggregate;

class User implements IKeyMap
{
	const PATH_FORMAT = '/user/%s';
	const USER_DIR = 'user/';

	private $mFingerprint;
	private $mUserID;

	public function __construct($userFingerprint, $userID=null) {
		if(!$userFingerprint)
			throw new \InvalidArgumentException("Invalid Fingerprint");
		$this->mFingerprint = $userFingerprint; // preg_replace('/[^\w\d]*/', '', $userFingerprint);
		$this->mUserID = $userID;
	}

	public function getFingerprint() {
		return $this->mFingerprint;
		//return $this->getPGPKey()->getFingerprint($stripSpaces);
	}

	public function getUserID() {
		return $this->mUserID ?: substr($this->mFingerprint, -8);
	}

	public function getRequestPath() {
		return sprintf(self::PATH_FORMAT, substr($this->getFingerprint(), -8));
	}

	/**
	 * @param IRequest $Request
	 * @throws \BC\PGP\Commands\Exceptions\PGPNotFoundException
	 * @throws \BC\PGP\Commands\Exceptions\PGPSearchException
	 * @return PGPSearchCommand
	 */
	public function getPGPKey(IRequest $Request) {
		$UserSearch = new PGPSearchCommand($this->getFingerprint(), '');
		$UserSearch->addKeyRing(PGPConfig::$KEYRING_USER);
		return $UserSearch->queryOne($Request);
	}

	/**
	 * Map data to the key map
	 * @param IKeyMapper $Map the map inst to add data to
	 * @internal param \CPath\Request\IRequest $Request
	 * @internal param \CPath\Request\IRequest $Request
	 * @return void
	 */
	function mapKeys(IKeyMapper $Map) {
		$Map->map('fingerprint', $this->getFingerprint());
		$Map->map('userID', $this->getUserID());

		$Request = $Map;
		if($Request instanceof IRequestAggregate) {
			$Request = $Request->getWrappedRequest();
			$Map->map('pgp', $this->getPGPKey($Request));
		}
	}

	// Static

	/**
	 * @param $userSearch
	 * @param string $searchMode
	 * @throws \BC\PGP\Commands\Exceptions\PGPNotFoundException
	 * @throws \BC\PGP\Commands\Exceptions\PGPSearchException
	 * @return PGPSearchCommand
	 */
	public static function search($userSearch, $searchMode = '=') {
		$UserSearch = new PGPSearchCommand($userSearch, $searchMode);
		$UserSearch->addKeyRing(PGPConfig::$KEYRING_USER);
		return $UserSearch;
	}

	public static function searchFirst(IRequest $Request, $userSearch, $searchMode = '=') {
		$UserSearch = self::search($userSearch, $searchMode);
		$UserSearch = $UserSearch->queryOne($Request);
		return $UserSearch->getUser();
	}
}